import axios from 'axios'
const cart = {
  state: {
    list: JSON.parse(localStorage.getItem('state')).cart.list || [],
    total: 0,
    // 购物车列表数组
    cartList: JSON.parse(localStorage.getItem('state')).cart.cartList || [],
  },
  mutations: {
    // 初始化请求数据
    init_list(state, data) {
      state.list = data.list
      state.total = data.total
    },
    // 加入购物车函数
    to_cart(state, item) {
      // 1. 第一个，数据不能重复
      // 2. 如果第一次加入购物车。让他的数量变为1
      const goods = state.cartList.find((v) => v.id === item.id)
      if (goods) {
        goods.count++
      } else {
        item.count = 1
        state.cartList.push(item)
      }
    },
    // +
    add_item(state, item) {
      item.count++
    },
    // -
    reduce_item(state, item) {
      if (item.count <= 1) {
        if (window.confirm('确定删除吗?')) {
          state.cartList.splice(
            state.cartList.findIndex((v) => v.id === item.id),
            1
          )
        }
        return
      }
      item.count--
    },
  },
  actions: {
    // 购物车接口
    async getCartList({ commit }, params) {
      try {
        const res = await axios.get('/api/cart', { params })
        if (res.data.code === 0) {
          commit('init_list', {
            list: res.data.data.list,
            total: res.data.data.total,
          })
          return { code: 0, msg: 'success' }
        } else {
          return { code: -1, msg: 'fail' }
        }
      } catch (err) {}
    },
  },
  getters: {
    totalPrice(state) {
      // state.totalPrice = state.cartList.reduce((num, item) => {
      //   return num + item.count * item.price
      // }, 0)
      return state.cartList.reduce((num, item) => {
        return num + item.count * item.price
      }, 0)
    },
  },
}

export default cart
